#include "includes.h"
#include "check.h"


#define DATA_NUM	80
data uint8_t Buf0[DATA_NUM];
data uint8_t LedCnt;
data uint8_t ChkCnt0;
data uint16_t ChkCnt1;
bit ChkTmr0Res;
bit ChkTmr1Res;
bit ChkTmr2Res;
#define IDATA_NUM	128
idata uint8_t Buf1[IDATA_NUM] _at_ 0x80;

#define PAT_NUM	8
code uint8_t Pat[PAT_NUM]={0xAA, 0x55, 0xA5, 0x5A, 0x69, 0x96, 0xC3, 0x3C};


void CheckInit(void)
{
	P0M0 |= BIT0;
	LED0 = 1;
	AdcInit(BIT2);
	Timer0Init(200);
	Timer1Init(200);
	Timer2Init(60000);
	P1M0 &= ~(BIT0|BIT1);			//Set P10 P11 as input
	P2M0 &= ~(BIT0|BIT1);			//Set P20 P21 as input
	Pwm0Init(1000, 500);
	Pwm1Init(1000, 500);
	Pwm2Init(1000, 500);
	Pwm3Init(1000, 500);
//	
//	WdtInit();
	EA = 1;
}

void CheckHandle(void)
{
	if(ChkCnt0>20)						//100ms
	{
		ChkCnt0 = 0;
		CheckRam();
		CheckRom();
		CheckTmr();
		CheckPwm();
	}
	if(ChkCnt1>1600)					//8s
	{
		ChkCnt1 = 0;
		CheckDee();
	}
	if(LedCnt>20)							//100ms
	{
		LedCnt = 0;
		
	}
}

////////////////////////////////////////////////////
void CheckTmr(void)
{
	if(ChkTmr0Res)
		CheckErr(ERR_TMR0);
	if(ChkTmr1Res)
		CheckErr(ERR_TMR1);
	if(ChkTmr2Res)
		CheckErr(ERR_TMR2);
	ChkTmr0Res = 1;
	ChkTmr1Res = 1;
	ChkTmr2Res = 1;
}

void CheckRam(void)
{
	uint8_t i;
	uint8_t j;
	
	for(j=0;j<PAT_NUM;j++)
	{
		//DATA
		for(i=0;i<DATA_NUM;i++)
		{
			Buf0[i] = Pat[j];
		}
		for(i=0;i<DATA_NUM;i++)
		{
			if(Buf0[i]!=Pat[j])
			{
				CheckErr(ERR_RAM);
			}
		}
		//IDATA
		for(i=0;i<IDATA_NUM;i++)
			Buf1[i] = Pat[j];
		for(i=0;i<IDATA_NUM;i++)
		{
			if(Buf1[i]!=Pat[j])
			{
				CheckErr(ERR_RAM);
			}
		}
	}
}

void CheckRom(void)
{
	uint16_t i;
	uint8_t j;
	uint16_t sum;
	
	sum = 0;
	for(i=0;i<256;i++)
	{
		PflRd(0xE000+i*32, &Buf0[0], 32);
		for(j=0;j<32;j++)
		{
			sum += Buf0[j];
		}
	}
	if(sum!=0xDC65)
	{
		CheckErr(ERR_ROM);
	}
}

void CheckPfl(void)
{
	
}

void CheckDee(void)
{
	uint8_t i, j, k;
	
	for(i=0; i<PAT_NUM; i++)
	{
		for(j=0; j<8; j++)
		{
			for(k=0; k<16; k++)
			{
				Buf0[k] = Pat[i];
			}
			DeeWr(DEE_ADDR+j*16, &Buf0[0], 16);
		}
		for(j=0; j<8; j++)
		{
			for(k=0; k<16; k++)
			{
				Buf0[k] = 0;
			}
			DeeRd(DEE_ADDR+j*16, &Buf0[0], 16);
			for(k=0; k<16; k++)
			{
				if(Buf0[k]!=Pat[i])
				{
					CheckErr(ERR_DEE);
				}
			}
		}
	}
}

void CheckPwm(void)
{
	while(PWM0);
	while(!PWM0);
	while(PWM1);
	while(!PWM1);
	while(PWM2);
	while(!PWM2);
	while(PWM3);
	while(!PWM3);
}

void CheckWdt(void)
{
	WdtFed();
}


void CheckErr(uint8_t err_code)
{
	Buf0[0] = 0xEE;
	Buf0[1] = err_code;
	Buf0[2] = 0xEE;
	DeeWr(DEE_ADDR, &Buf0[0], 3);
	WdtDis();
	while(1);
}




